﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;

namespace dotnetty_client2
{
    internal class DecoderHandler : ByteToMessageDecoder
    {
        private const int FIXED_LENGTH = 12;
        private const int PACK_HEAD_LEN = 4;

        //public ATcpConnection2()
        //{
        //    this.maxPackLength = 16 * (1024 * 1024);
        //}

        private int maxPackLength = int.MaxValue;
        private int currentReadLength = PACK_HEAD_LEN;
        private PackPart currentReadPart = PackPart.Head;

        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
        {
            while (true)
            {
                if (input.ReadableBytes < 4)
                {
                    return;
                }

                if (this.currentReadPart == PackPart.Head)
                {
                    this.currentReadLength = input.ReadInt();
                    if (this.currentReadLength > this.maxPackLength)
                        throw new Exception("pack length error!" + this.currentReadLength.ToString());
                    this.currentReadPart = PackPart.Body;
                }
                else if (this.currentReadPart == PackPart.Body)
                {
                    var buf = input.ReadBytes(this.currentReadLength);
                    output.Add(buf);

                    this.currentReadLength = PACK_HEAD_LEN;
                    this.currentReadPart = PackPart.Head;
                }
            }
            

            



            //if (input.ReadableBytes < 12)
            //{
            //    return; // (3)
            //}
            //output.Add(input.ReadBytes(12)); // (4)
        }

        private enum PackPart : byte
        {
            Head,
            Body,
        }
    }
}
